/**
 * Created by wtfssd on 2017/9/15.
 */

import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {
    StyleSheet, Text, View, AsyncStorage, SectionList, Image, TouchableOpacity, TextInput
} from 'react-native'
import SimpleLineIcon from 'react-native-vector-icons/SimpleLineIcons'
import {connect} from 'react-redux'
import {InputItem, Popup, Toast, List} from 'antd-mobile'
import NavigationBar from 'react-native-navbar'
import {Actions, ActionConst} from 'react-native-router-flux'
import CommonStyle, {SCREEN, Color} from '../../assets/styles/index'

import {MyIcon, Line, Counter, PayMethod, BackButton} from '../common/index'

import {countInCart} from '../../utils/tools'

import BottomBar from './bottomBar'

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let maskProps;
if (isIPhone) {
    // Note: the popup content will not scroll.
    maskProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

class Page extends Component {
    message = null;

    constructor(props) {
        super(props);
        this.state = {
            refreshing: false,
            address: null,
            coupon: null,
        };
    }

    componentWillMount() {

    }


    goTo = (key, opt = {}) => {
        Actions.push(key, opt)
    };
    selectCouponCallBack = (coupon) => {
        this.setState({coupon})
    };

    /*刷新*/
    onRefresh = () => {
        this.setState({refreshing: true});
        setTimeout(() => {
            this.setState({refreshing: false});
        }, 2000)
    };
    /*分组 item点击*/
    onPressItem = (props) => {
        // console.log(props);
    };


    onTextChange = (message) => {
        this.message = message;
    };


    /*数据源主键 */
    keyExtractor = (item, index) => item.id;
    /*分组头*/
    renderSection = ({section: {title}}, index) => {
        return (
            <View style={Styles.section}>
                <MyIcon name="shop" color="#499DF5" size={20 / 375 * SCREEN.width}/>
                <Text style={[
                    CommonStyle.text1,
                    {
                        marginLeft: 10 / 375 * SCREEN.width,
                        marginTop: -3 / 375 * SCREEN.width
                    }
                ]}>{title}</Text>
            </View>

        )
    };
    /*分组 item*/
    renderItem = ({item}, index) => {
        return (
            <TouchableOpacity onPress={this.onPressItem.bind(this, item)} activeOpacity={0.9}>
                <View style={Styles.product}>
                    <Image source={{uri: item.preview}} style={Styles.productIcon}/>
                    <View style={Styles.itemRightContent}>
                        <Text>{item.name}</Text>
                        <Text>{item.spec}</Text>
                        <View style={Styles.price}>
                            <Text style={[CommonStyle.priceText]}>¥{item.price}</Text>
                            <Counter count={item.pivot.count} disabled/>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };
    /*分组分割线*/
    renderSectionSeparatorComponent = (item, index) => {
        if (item.leadingItem) {
            return <Line height={10}/>
        }
        return <Line height={1}/>;

    };

    renderListHeader = () => {
        const {defaultAddress} = this.props.auth;
        const {address} = this.state;
        return (
            <TouchableOpacity onPress={Actions.addressList.bind(null, {
                    data: {
                        type: 'pick', onPicked: (address) => {
                            this.setState({address})
                        }
                    }
                }
            )}>
                {defaultAddress ? (() => {
                    const _address = address ? address : defaultAddress;
                    return (
                        <View>
                            <View style={Styles.listHeader}>
                                <Text style={[CommonStyle.text1, {fontSize: 16}]}>{_address.accepter}
                                    <Text>{_address.telphone}</Text></Text>
                                <Text style={[CommonStyle.text2, {fontSize: 13, paddingVertical: 4}]}
                                      numberOfLines={2}>{`${_address.address}${_address.address_detail}`}</Text>
                            </View>
                            <Image source={require('../../assets/image/color.png')}
                                   style={{height: 6.5, backgroundColor: 'white'}}/>
                            <Line height={10} backgroundColor="#F2F2F2"/>
                        </View>
                    )
                })() : (() => {
                    return (
                        <View style={Styles.noData}>
                            <Text>暂无收货地址</Text>
                        </View>
                    )
                })()}
            </TouchableOpacity>
        )
    };
    renderListFooter = () => (

        <List>
            {/*<View style={Styles.listFooter}>*/}
            {/*<Text</Text>*/}
            {/*<Text style={{color: '#999999', marginLeft: 10}}>5元</Text>*/}

            {/*</View>*/}

            <List.Item extra={'5元'}>
                配送费
            </List.Item>
            <List.Item arrow={'horizontal'}
                       extra={this.state.coupon?this.state.coupon.name:'无'}
                       onClick={this.goTo.bind(this, 'couponList', {callBack: this.selectCouponCallBack})}>
                优惠券
            </List.Item>

            {this.props.cart.coupon ? <List.Item extra={this.props.cart.coupon.name}>优惠券</List.Item> : null}

            <InputItem style={{flex: 1}}
                       size='small'
                       placeholder='选填：对本次交易的说明'
                       clearButtonMode='while-editing'
                       onChange={this.onTextChange}
            />
        </List>

    );


    doPay(method) {
        Popup.hide();
        const {defaultAddress, profile} = this.props.auth;
        if (!profile.alipay && !profile.wx_user) {
            Actions.profile();
            return;
        }


        const {address} = this.state;
        let address_id = null;
        if (!defaultAddress && !address) {
            Toast.fail('请输入收货地址');
            return;
        } else {
            if (address) {
                address_id = address.id;
            } else if (defaultAddress) {
                address_id = defaultAddress.id;
            }
        }

        let payload = {
            user_id: this.props.auth.profile.member_id,
            address_id,
            markets_id: this.props.cart.selectMarket.id,
            payment: method === 'alipay' ? 1 : 2,
            coupon_id: 0
        };

        console.log(payload);
        if (this.state.coupon) {
            payload.coupon_id = this.state.coupon.id
        }
        if (this.message) {
            payload.message = this.message
        }
        this.props.dispatch({
            type: 'cart/pay',
            payload
        })
    }

    onSubmit() {
        Popup.show(
            <PayMethod onPay={this.doPay.bind(this)}/>, {animationType: 'slide-up', maskProps, maskClosable: true}
        )
    }

    render() {
        return (
            <View style={Styles.container} behavior={'padding'}>
                <NavigationBar tintColor={Color.primary}
                               statusBar={{style: 'light-content'}}
                               title={{title: this.props.title, tintColor: 'white'}}
                               leftButton={<BackButton/>}
                />

                <SectionList sections={this.props.cart.list.map((item, index) => ({
                    key: item.store_id,
                    data: item.sub,
                    title: "轻生活"
                }))}
                             renderSectionHeader={this.renderSection}
                             keyExtractor={this.keyExtractor}
                             refreshing={this.state.refreshing}
                             onRefreshr={this.onRefresh}
                             style={Styles.list}
                             SectionSeparatorComponent={this.renderSectionSeparatorComponent}
                             ItemSeparatorComponent={Line.bind(null, {height: 1})}
                             renderItem={this.renderItem}
                             ListHeaderComponent={this.renderListHeader}
                             ListFooterComponent={this.renderListFooter}
                             keyboardDismissMode="on-drag"

                />
                <BottomBar count={countInCart(this.props.cart.list)} total={this.props.cart.total + 5} type='submit'
                           onSubmit={this.onSubmit.bind(this)}/>
            </View>
        )
    }
}

const Styles = StyleSheet.create({
    container: {
        display: 'flex',
        flex: 1,
    },
    list: {
        backgroundColor: '#F2F2F2',
        flex: 1,
        width: SCREEN.width
    },
    section: {
        display: 'flex',
        height: 29 / 375 * SCREEN.width,
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 10 / 375 * SCREEN.width,
        backgroundColor: 'white',
    },
    product: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        height: 93.6 / 375 * SCREEN.width,
        paddingLeft: 19.4 / 375 * SCREEN.width,
        backgroundColor: 'white'
    },
    productIcon: {
        height: 80.8 / 375 * SCREEN.width,
        width: 80.8 / 375 * SCREEN.width,
        borderRadius: 40.4 / 375 * SCREEN.width
    },
    itemRightContent: {
        display: 'flex',
        height: '100%',
        flex: 1,
        justifyContent: 'space-around',
        paddingLeft: 20 / 375 * SCREEN.width,
        paddingRight: 10 / 375 * SCREEN.width,
        paddingHorizontal: 10 / 375 * SCREEN.width
    },
    price: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    listHeader: {
        display: 'flex',
        padding: 10,
        backgroundColor: 'white'
    },
    listFooter: {
        display: 'flex',
        flexDirection: 'row',
        backgroundColor: 'white',
        alignItems: 'center',
        padding: 10,
    },
    noData: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: 100,
    }

});

export default connect(
    ({cart, auth}) => ({cart, auth})
)(Page)



